
#-*- coding:utf-8 -*-

import json
from django.http import HttpResponse
from comunidadcyt.Registration_Users.models import User, UserProfile
from django.core.exceptions import ObjectDoesNotExist

def listarPersonal(request):
    jsonRet = {"success": True}
    data = []
    try:
        perfiles = UserProfile.objects.all().order_by('cargo__Jerarquia', 'cargo__Cargo', 'user__first_name', 'user__last_name')
        for perfil in perfiles:
            user = perfil.user

            if user.is_active:
                cargos = []

                for cargo in perfil.cargo.all().order_by('Jerarquia'):
                    cargos.append({"id": str(cargo.id), "nombre": cargo.Cargo, "jerarquia": cargo.Jerarquia})

                personal = {
                    "id": str(user.id),
                    "titulo": perfil.titulo,
                    "nombre": user.first_name,
                    "apellido": user.last_name,
                    "cargos": cargos
                }

                data.append(personal)
        jsonRet['data'] = data
    except ObjectDoesNotExist:
        jsonRet = {"success": False, "data":{"message": "No se encontraron personales."}}
    except Exception as e:
        jsonRet = {"success": False, "data":{"message": "Excepcion: %s" % e.message}}

    return HttpResponse(json.dumps(jsonRet))

def perfilUsuario(request, object_id):
    jsonRet = {"success": True}
    try:
        user = User.objects.get(id = object_id)
        perfil = user.get_profile()
        if perfil is None:
            jsonRet = {"success": False, "data":{"message": "No se encontro el usuario solicitado."}}
        else:
            cargos = []

            for cargo in perfil.cargo.all().order_by('Jerarquia'):
                cargos.append({"id": str(cargo.id), "nombre": cargo.Cargo, "jerarquia": cargo.Jerarquia})

            data = {
                "id": str(user.id),
                "titulo": perfil.titulo,
                "nombre": user.first_name,
                "apellido": user.last_name,
                "telefono": perfil.telefono,
                "interno": perfil.interno,
                "email": user.email,
                "activo": user.is_active,
                "foto": perfil.foto.url,
                "cargos": cargos
            }

            jsonRet['data'] = data
    except ObjectDoesNotExist:
        jsonRet = {"success": False, "data":{"message": "No se encontro el usuario solicitado."}}
    except Exception as e:
        jsonRet = {"success": False, "data":{"message": "Excepcion: %s" % e.message}}

    return HttpResponse(json.dumps(jsonRet))
